let miotLinkBaseNativeJs_client = null,
  miotLinkBaseNativeJs_puId = null,
  miotLinkBaseNativeJs_modelId = null,
  miotLinkBaseNativeJs_kindId = null,
  miotLinkBaseNativeJs_state = null,
  miotLinkBaseNativeJs_mac = null,
  miotLinkBaseNativeJs_puNickName = null,
  miotLinkBaseNativeJs_cuId = null,
  miotLinkBaseNativeJs_cuName = null,
  miotLinkBaseNativeJs_cuLocation = null,
  miotLinkBaseNativeJs_userdata = null,
  miotLinkBaseNativeJs_language = null,
  miotLinkBaseNativeJs_sequence = null,
  miotLinkBaseNativeJs_init = 'uninit'
const miotLinkBaseNativeJs_payRes = 'payRes'
const define_miotlink_init =
  '{"code":"init","data":{"getInitPuData":"true","hiddenPluginTitle":"true","getLanguage":"true","getCuInfo":"true","getStatusBarInfo":"false"}}'
const define_miotlink_returnDeviceList = '{"code":"returnDeviceList"}'

const define_miotlink_code_initRes = 'initRes', // initRes = 初始化返回
  define_miotlink_code_notifyUartData = 'notifyUartData',
  define_miotlink_code_notifyDeviceState = 'notifyDeviceState',
  define_miotlink_code_getAdditionalInfoRes = 'additionalInfoRes',
  define_miotlink_code_goBackRes = 'goBackRes'

/**********  安卓客戶端 *******************/
window.receiverDeviceData = function (data) {
  // 监听 Android,IOS 端的数据-yu
  console.log('监听客户端的数据', data)
  if (miotLinkBaseNativeJs_init !== 'initOk') {
    console.log('45555')
    return
  }
  miotLinkBaseNativeJs_receive(data)
}

export function miotLinkBaseNativeJs_initAndroid() {
  console.log('调用了安卓数据----')
  //android 端初始化
  try {
    console.log('miotLinkBaseNativeJs_initAndroid============= ', define_miotlink_init)
    const androidClientData =
      // miotlink_js_bridge.receiveHtmlData => js向框架传递数据
      miotlink_js_bridge.receiveHtmlData(define_miotlink_init)

    console.log('androidClientData==========', androidClientData)
    miotLinkBaseNativeJs_receive(androidClientData)
  } catch (e) {
    ////alert("and:"+e);
  }
}

function miotLinkBaseNativeJs_sendToAndroid(data) {
  console.log('miotLinkBaseNativeJs_sendToAndroid=======', data)
  console.log(miotLinkBaseNativeJs_init)
  if (miotLinkBaseNativeJs_init !== 'initOk') {
    console.log('Android-未正确初始化，发送数据不予处理')
    //alert("Android-未正确初始化，发送数据不予处理！");
    return
  }
  try {
    console.log(2222)
    return miotlink_js_bridge.receiveHtmlData(data)
  } catch (e) {}
}

/***********  IOS客户端 ******************/
export function miotLinkBaseNativeJs_initIos() {
  console.log(2)
  //TODO
  miotLinkBaseNativeJs_sendToIos(define_miotlink_init)
}

function miotLinkBaseNativeJs_sendToIos(data) {
  connectWebViewJavascriptBridge(function (bridge) {
    bridge.callHandler('changeNaviStatus', data, function (response) {
      miotLinkBaseNativeJs_receive(response)
    })
    bridge.registerHandler('receiverDeviceData', function (data) {
      miotLinkBaseNativeJs_receive(data)
    })
    if (miotLinkBaseNativeJs_init === 'uninit') {
      bridge.init(function (data, responseCallback) {
        miotLinkBaseNativeJs_receive(data)
      })
      bridge.registerHandler('receiverDeviceData', function (data) {
        miotLinkBaseNativeJs_receive(data)
      })
    }
  })
}
/**
 * 连接WebViewJavascriptBridge
 * 在 native 端和 webview 端注册 Bridge
 *
 */
function connectWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    return callback(WebViewJavascriptBridge)
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback)
  }
  window.WVJBCallbacks = [callback]
  const WVJBIframe = document.createElement('iframe')
  WVJBIframe.style.display = 'none'
  WVJBIframe.src = 'https://__bridge_loaded__'
  document.documentElement.appendChild(WVJBIframe)
  setTimeout(function () {
    document.documentElement.removeChild(WVJBIframe)
  }, 0)
  if (window.WebViewJavascriptBridge) {
    callback(WebViewJavascriptBridge)
  } else {
    document.addEventListener(
      'WebViewJavascriptBridgeReady',
      function () {
        callback(WebViewJavascriptBridge)
      },
      false
    )
  }
}

// TODO
// 初始化，喵喵屋返回的数据
function miotLinkBaseNativeJs_initData(clientInitData) {
  miotLinkBaseNativeJs_client = clientInitData.client
  miotLinkBaseNativeJs_language = clientInitData.language
  miotLinkBaseNativeJs_puId = clientInitData.pu.puId
  miotLinkBaseNativeJs_kindId = clientInitData.pu.kindId
  miotLinkBaseNativeJs_modelId = clientInitData.pu.modelId
  miotLinkBaseNativeJs_userdata = clientInitData.pu.userdata
  miotLinkBaseNativeJs_state = clientInitData.pu.state
  miotLinkBaseNativeJs_mac = clientInitData.pu.mac
  miotLinkBaseNativeJs_puNickName = clientInitData.pu.puNickName
  miotLinkBaseNativeJs_cuId = clientInitData.cu.cuId
  miotLinkBaseNativeJs_cuName = clientInitData.cu.cuName
  miotLinkBaseNativeJs_cuLocation = clientInitData.cu.location

  console.log('miotLinkBaseNativeJs_puNickName=======', miotLinkBaseNativeJs_puNickName)
  useStore.deviceInfo = clientInitData

  console.log('useStore=====', useStore)

  if (
    clientInitData.hasNotchInScreen === 'true' ||
    clientInitData.hasNotchInScreen === true ||
    clientInitData.statusBarHeight
  ) {
    console.log('clientInitData.statusBarHeight======', clientInitData.statusBarHeight)
    // store.commit('commitAppData', {
    //   headerTop: 88 / 2
    // })
  }
  miotLinkBaseNativeJs_init = 'initOk'
}

function miotLinkBaseNativeJs_receive(data) {
  console.log('miotLinkBaseNativeJs_receive=============', data)
  if (data == null || data === '') return
  try {
    var dataJsonObj = JSON.parse(data)
    console.log('dataJsonObj=====', dataJsonObj)
  } catch (e) {}

  let code = dataJsonObj.code.toLowerCase()

  if (code === define_miotlink_code_goBackRes.toLowerCase()) {
    receiveFromNative_goBackRes()
    return
  }
  const clientDataJsonObj = dataJsonObj.data
  if (
    clientDataJsonObj.puId != miotLinkBaseNativeJs_puId &&
    code != define_miotlink_code_getAdditionalInfoRes.toLowerCase() &&
    code != miotLinkBaseNativeJs_payRes.toLowerCase() &&
    code != 'airfruit'
  ) {
    console.log('code==', code)
    //alert("此消息非本设备消息！监听：" + miotLinkBaseNativeJs_puId + ",收到：" + clientDataJsonObj.puId);
    return
  }

  if (code === define_miotlink_code_initRes.toLowerCase()) {
    //收到初始化返回
    console.log('收到初始化返回')
    miotLinkBaseNativeJs_initData(clientDataJsonObj)
  } else if (code === define_miotlink_code_notifyDeviceState.toLowerCase()) {
    //收到设备上下线
    console.log('收到设备上下线')
    receiveFromNative_deviceState(clientDataJsonObj.state, clientDataJsonObj.sequence)
  } else if (code === define_miotlink_code_notifyUartData.toLowerCase()) {
    //收到串口数据
    console.log('收到串口数据')
    // receiveFromNative_uartData('F2 F2 F3 05 00 13 02 01 20 2E 7E'.replace(/\s+/g, ''))
    receiveFromNative_uartData(clientDataJsonObj.uart.replace(/\s+/g, ''))
  } else if (code === define_miotlink_code_getAdditionalInfoRes.toLowerCase()) {
    //收到附加信息
    console.log('收到附加信息')
    receiveFromNative_additionalInfoRes(clientDataJsonObj)
  }
}

function sendToNative(data) {
  if (miotLinkBaseNativeJs_client === 'Android') {
    return miotLinkBaseNativeJs_sendToAndroid(data)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    return miotLinkBaseNativeJs_sendToIos(data)
  }
}

function receiveFromNative_goBackRes() {
  console.log('333')
  sendToNative_returnDeviceList()
}

function receiveFromNative_pay(payinfo) {
  //			alert(payinfo);
}

function receiveFromNative_additionalInfoRes(additionalInfo) {
  //			alert(additionalInfo);
  //alert("请重写receiveGetAdditionalInfoRes 收到附加信息 方法，实现H5端的界面显示。additionalInfo = " + JSON.stringify(additionalInfo));
  let miotPM2_5, city, miotSD, miotTemperature, miotAqi, miotIcon
  if (additionalInfo.hasOwnProperty('values')) {
    //alert("11="+JSON.stringify(additionalInfo.values) );
    miotPM2_5 = additionalInfo.values.miotPM2_5
    city = additionalInfo.values.city
    miotSD = additionalInfo.values.miotSD //湿度
    miotTemperature = additionalInfo.values.miotTemperature //温度
    miotAqi = additionalInfo.values.miotAqi //Aqi
    miotIcon = additionalInfo.values.miotIcon //天气
  } else if (additionalInfo.hasOwnProperty('data')) {
    //alert("21="+additionalInfo.values);
    miotPM2_5 = additionalInfo.data.values.miotPM2_5
    city = additionalInfo.data.values.city
    miotSD = additionalInfo.data.miotSD //湿度
    miotTemperature = additionalInfo.data.miotTemperature //温度
    miotAqi = additionalInfo.data.miotAqi //Aqi
    miotIcon = additionalInfo.data.miotIcon //天气
  }
  var city_location = city.split(',')

  $('#location_name').text(city_location[1])
  store.commit('commitAppData', {
    cityAQI: miotAqi,
    cityPM25: miotPM2_5,
    cityWenDu: miotTemperature,
    cityShiDu: miotSD,
    city: city_location[1]
  })
}

function receiveFromNative_deviceState(state, sequence) {
  miotLinkBaseNativeJs_state = state
  miotLinkBaseNativeJs_sequence = sequence
  //alert("请重写receiveDeviceState方法，实现设备上下线的界面显示。state = " + state + ",puId = " + miotLinkBaseNativeJs_puId);
}

function receiveFromNative_uartData(data) {
  try {
    if (window.queryState) {
      receive(data)
    }
  } catch (e) {
    alert(e)
  }
}

function sendToNative_returnDeviceList() {
  if (miotLinkBaseNativeJs_client === 'Android') {
    miotLinkBaseNativeJs_sendToAndroid(define_miotlink_returnDeviceList)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    miotLinkBaseNativeJs_sendToIos(define_miotlink_returnDeviceList)
  } else {
    const u = navigator.userAgent
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
    if (isAndroid === true) {
      miotLinkBaseNativeJs_sendToAndroid(define_miotlink_returnDeviceList)
    } else if (isiOS === true) {
      miotLinkBaseNativeJs_sendToIos(define_miotlink_returnDeviceList)
    }
  }
}

/**
 * @description 发送串口数据
 * @param {string} 串口 例如：F1F1000102037E
 */
export const sendToNative_sendUartData = function (hexUartData) {
  console.log(hexUartData, 'hexUartData')
  hexUartData = hexUartData.replace(/\s+/g, '')
  const data =
    '{"code":"sendDeviceUartData","data":{"puId":"' +
    miotLinkBaseNativeJs_puId +
    '","uartDataType":"0","uartData":"' +
    hexUartData +
    '"}}'

  console.log('我发送的数据=======', data)
  console.log('miotLinkBaseNativeJs_client=========', miotLinkBaseNativeJs_client)
  if (miotLinkBaseNativeJs_client === 'Android') {
    console.log(111)
    miotLinkBaseNativeJs_sendToAndroid(data)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    miotLinkBaseNativeJs_sendToIos(data)
  }
}
sendToNative_sendUartData('F1F10204000c0103167E')
function sendToNative_pay(payinfo) {
  const data = '{"code":"pay","data":' + payinfo + '}'
  //			alert(data);
  if (miotLinkBaseNativeJs_client === 'Android') {
    miotLinkBaseNativeJs_sendToAndroid(data)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    miotLinkBaseNativeJs_sendToIos(data)
  }
}

function doLoadAction(uartData, params) {
  sendToNative_sendUartData(uartData)
}

function ml_parseUartData(playload, byteDefineCodeArray, byteDefineKeyArray) {
  console.log(playload, 'playload')
  //				console.log("parseUartData _____  playload = " + playload + ",byteDefineCodeArray=" + byteDefineCodeArray + ",byteDefineKeyArray=" + byteDefineKeyArray);
  if (
    typeof playload == 'undefined' ||
    playload == null ||
    playload === '' ||
    byteDefineKeyArray == null ||
    byteDefineKeyArray.length === 0 ||
    byteDefineKeyArray.length !== byteDefineCodeArray.length
  ) {
    //					console.log("parseUartData _____  params error");
    return null
  }
  playload = playload.toUpperCase().replace(/ /g, '')
  let playloadUartDataJson = ''
  let subStrStart = 0
  for (let i = 0; i < byteDefineCodeArray.length; i++) {
    const byteHexStrLength = byteDefineCodeArray[i] * 2
    const byteKey = byteDefineKeyArray[i]
    const value = playload.substr(subStrStart, byteHexStrLength)
    if (i !== byteDefineCodeArray.length - 1) {
      playloadUartDataJson += '"' + byteKey + '":"' + parseInt(value, 16) + '",'
    } else {
      playloadUartDataJson += '"' + byteKey + '":"' + parseInt(value, 16) + '"'
    }
    subStrStart += byteHexStrLength
  }

  // return playloadUartDataJson
  return JSON.parse('{' + playloadUartDataJson + '}')
}

Date.prototype.format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

function receive(data) {
  let d = parseData.parseProtocol(data)
  d['updateTime'] = new Date().format('yyyy-MM-dd hh:mm:ss')
  let dsSwitch = (d['dingShi'] + '').padStart(10, '0').substring(0, 2)
  d['dingShiSwitch'] = parseInt(dsSwitch) + ''
  store.commit('commitAppData', d)
}
